import { defHttp } from '/@/common/util/axios';
import { useUserStore } from '/@/store/modules/user';
import { getAuthCache } from '/@/common/util/localCache';
import { getDictItems4Code } from '/@/api/common/api';
import { data_dict } from '/@/common/constant/cacheConst';

/**
 * 从缓存中获取字典配置
 * @param code
 */
export const getDictItemsByCode = (code) => {
  const userStore = useUserStore();
  const dictItems = userStore.getAllDictItems;
  if (null != dictItems && typeof dictItems === 'object' && dictItems[code]) {
    return dictItems[code];
  }
  //兼容以前的旧写法
  if (getAuthCache(data_dict) && getAuthCache(data_dict)[code]) {
    return getAuthCache(data_dict)[code];
  }
};
/**
 * Popup字典翻译方法
 * @param text
 * @param code
 */
export const getPopDictByCode = (text, codeStr) => {
  const [code, dictCode, dictText] = codeStr.split(',');
  if (!code || !dictCode || !dictText) {
    return [];
  }
  return defHttp.get(
    { url: `/online/api/cgreportGetDataPackage`, params: { code, dictText, dictCode, dataList: text } },
    { isTransformResponse: false }
  );
};
/**
 * 获取字典数组
 * @param dictCode 字典Code
 * @return List<Map>
 */
export const initDictOptions = (code) => {
  //1.优先从缓存中读取字典配置
  if (getDictItemsByCode(code)) {
    return new Promise((resolve, reject) => {
      resolve(getDictItemsByCode(code));
    });
  }
  //2.获取字典数组
  if (code.indexOf(',') > 0 && code.indexOf(' ') > 0) {
    // 编码后类似sys_user%20where%20username%20like%20xxx' 是不包含空格的,这里判断如果有空格和逗号说明需要编码处理
    code = encodeURI(code);
  }
  return getDictItems4Code(code);
};
